package com.czk.bootlettuce.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.List;

/**
 * 获取ip
 *
 * @Author:ChenZhangKun
 * @Date: 2021/10/8 10:23
 */
public class IpUtil {
    public static final String DEFAULT_IP = "127.0.0.1";

    /**
     * 直接根据第一个网卡地址作为其内网ipv4地址，避免返回 127.0.0.1
     *
     * @return
     */
    public static String getLocalIpByNetcard() {
        try {
            // 循环
            for (Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements(); ) {
                NetworkInterface networkInterface = e.nextElement();
                List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
                for (InterfaceAddress interfaceAddress : interfaceAddresses) {
                    if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                        continue;
                    }
                    if (interfaceAddress.getAddress() instanceof Inet4Address) {
                        Inet4Address inet4Address = (Inet4Address) interfaceAddress.getAddress();
                        return inet4Address.getHostAddress();
                    }
                }
            }
            return InetAddress.getLocalHost().getHostAddress();
        } catch (Exception exception) {
            throw new RuntimeException(exception.getMessage());
        }
    }

    public static void main(String[] args) {
        try {
            System.out.println(IpUtil.getLocalIpByNetcard());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
